<template>
    <div>
        <el-button class="back-btn" type="primary" icon="el-icon-arrow-left" plain style="margin-right: 25px" @click="goBack">返回</el-button>
        <div class="pdf-warp" ref="pdf" v-loading="loadState">
            <pdf v-for="page in pageCount"
                 :key="page"
                 :page="page"
                 :src="source"
            ></pdf>
        </div>
    </div>
</template>

<script>
    import pdf from "vue-pdf";

    export default {
        name: "PdfScrollPreviewer",
        components:{pdf},
        props:{
            src:String
        },
        data(){
            return{
                pageCount: 0,
                loadState: false,
                source: null,
            }
        },
        methods:{
            goBack(){
                this.$emit("exit");
            },onError(e){
                console.log(e);
                this.$alert("pdf文件加载失败。",'无法预览',{type:'error'});
                this.loadState = false;
            },
            open(src){
                src = src || this.src;
                if(!src) return undefined;
                this.loadState = true;
                const that = this;
                const task = pdf.createLoadingTask(src);
                console.log(task);
                task.promise.then((pdf)=>{
                    that.pageCount = pdf['numPages'];
                    that.source = task;
                    this.$refs.pdf.scrollTop = 0;
                    console.log("pdf已加载完成:",pdf);
                }).catch(e=>that.onError(e)).finally(()=>{
                    that.loadState = false;
                });
            },
        },
        mounted() {
            this.open();
        },
        watch:{
            src(v){
                this.open(v);
            }
        }
    }
</script>

<style scoped>
    .pdf-warp{
        overflow-y: scroll;
        position: absolute;
        top: 3px;
        left: 3px;
        right: 12px;
        bottom: 5px;
        z-index: 5;
        background-color: white;
    }
    .back-btn{
        position: absolute;
        top: 25px;
        right: 35px;
        z-index: 100;
    }
</style>
